package com.otitan.la.forest.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.otitan.la.forest.system.dto.UserOrgDTO;
import com.otitan.la.forest.system.entity.UserOrgEntity;
import com.otitan.la.forest.system.mapper.UserOrgMapper;
import com.otitan.la.forest.system.service.UserOrgService;
import com.otitan.webapp.framework.basepro.exception.code.BaseResponseCode;
import com.otitan.webapp.framework.basepro.model.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserOrgServiceImpl extends ServiceImpl<UserOrgMapper, UserOrgEntity> implements UserOrgService {

    @Resource
    private UserOrgMapper userOrgMapper;

    @Transactional
    @Override
    public DataResult add(UserOrgDTO userOrgDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        List<UserOrgEntity> userOrgEntityList = new ArrayList<>();
        List<String> userIds = userOrgDTO.getUserIds();
        userIds.forEach(userId -> {
            UserOrgEntity userOrgEntity = new UserOrgEntity();
            userOrgEntity.setOrgId(userOrgDTO.getOrgId());
            userOrgEntity.setUserId(userId);
            userOrgEntityList.add(userOrgEntity);
        });
        // 删除已存在的关联关系，防止主键冲突异常
        removeOrgAndUserId(userOrgDTO);
        boolean isSuccess = this.saveBatch(userOrgEntityList);
        return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.DATA_NOT_EXIST.getMsg());
    }

    private boolean removeOrgAndUserId(UserOrgDTO userOrgDTO) {
        LambdaQueryWrapper<UserOrgEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(UserOrgEntity::getOrgId, userOrgDTO.getOrgId())
                .in(UserOrgEntity::getUserId, userOrgDTO.getUserIds());
       return this.remove(queryWrapper);
    }

    @Override
    public DataResult batchDelete(UserOrgDTO userOrgDTO) {
        boolean isSuccess=removeOrgAndUserId(userOrgDTO);
        log.debug("\n>>>>>>>>> 【删除用户组织机构关系表】 <<<<<<<<<\n操作结果：{}，ids：{}\n>>>>>>>>> ---- <<<<<<<<<", isSuccess);
        return DataResult.success();
    }

    @Override
    public DataResult editor(UserOrgEntity userOrg, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        boolean isSuccess = this.updateById(userOrg);
        return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.DATA_NOT_EXIST.getMsg());
    }

    @Override
    public DataResult findPageData(long page, long size, UserOrgDTO userOrg) {
        Page pagePlug = new Page(page, size);
        LambdaQueryWrapper<UserOrgEntity> queryWrapper = Wrappers.lambdaQuery();
        IPage<UserOrgEntity> iPage = this.page(pagePlug, queryWrapper);
        return DataResult.success(iPage);
    }

    @Override
    public DataResult findOne(String id) {
        return DataResult.success(this.getById(id));
    }
}